<template>
  <view class="container">
    <u-navbar
      back-text=""
      title="登录"
      v-if="!isWeChatOfficial"
      :title-bold="true"
      color="#333"
    ></u-navbar>
    <image class="logo" :src="logo" mode="widthFix" />
    <view class="form">
      <!-- #ifdef H5 -->
      <view>
        <view class="inputBox">
          <input
            class="inpt phone"
            type="number"
            v-model="form.username"
            maxlength="11"
            @blur="mobileBlurFn"
            placeholder-class="placeholderStyle"
            placeholder-style="color: #D3DBE0;font-size: 34rpx;font-weight: normal;"
            placeholder="请输入手机号"
          />
          <cover-image
            v-if="form.username"
            @tap="clearFn"
            class="close"
            src="https://naoyuekang-weixindev.oss-cn-chengdu.aliyuncs.com/mine/close.png"
          ></cover-image>
        </view>
        <view
          class="inputBox pwd-box"
          v-if="form.type === userApi.LOGIN_TYPE_ENUM.PWD"
        >
          <input
            class="inpt code"
            :type="showPassword ? 'text' : 'password'"
            maxlength="20"
            v-model="form.code"
            placeholder-class="placeholderStyle"
            placeholder-style="color: #D3DBE0;font-size: 34rpx;font-weight: normal;"
            placeholder="请输入密码"
          />
          <u-icon
            :name="showPassword ? 'eye-fill' : 'eye-off'"
            size="40"
            @click="togglePassword"
            class="eye-icon"
          >
          </u-icon>
        </view>
        <view class="inputBox flex" v-else>
          <input
            class="inpt code"
            type="text"
            maxlength="6"
            v-model="form.code"
            placeholder-class="placeholderStyle"
            placeholder-style="color: #D3DBE0;font-size: 34rpx;font-weight: normal;"
            placeholder="请输入验证码"
          />
          <u-button
            type="warning"
            rapple
            size="mini"
            :custom-style="{ background: '#FF6C18', color: '#fff' }"
            @click="sendSmsCode"
          >
            {{ codeText }}</u-button
          >
          <u-verification-code
            ref="uCode"
            @change="codeChange"
          ></u-verification-code>
        </view>
        <u-button
          type="primary"
          class="hy-btn"
          ripple
          :custom-style="{ background: '#FF6C18', color: '#fff' }"
          @click="submit"
          >登录</u-button
        >

        <view class="loginType">
          <text
            @click="switchLoginType('SMS_CODE')"
            v-if="form.type === userApi.LOGIN_TYPE_ENUM.PWD"
            >验证码登录
          </text>
          <text v-else @click="switchLoginType('PWD')">密码登录 </text>
        </view>
        <!-- #ifdef H5 -->
        <u-button
          v-if="isWeChatOfficial"
          type="success"
          class="hy-btn wx"
          open-type="getPhoneNumber"
          ripple
          @click="handleWxWebLogin"
        >
          <text class="iconfont hy-icon-wechat"></text>
          微信快捷登录
        </u-button>

        <!-- #endif -->
        <view class="signuptips" @click="toRegister"
          >还没有账号？ <text> 点我立即注册</text></view
        >
      </view>
      <!-- #endif -->

      <view>
        <!-- #ifdef MP-WEIXIN -->
        <u-button
          type="primary"
          class="hy-btn wx"
          open-type="getPhoneNumber"
          ripple
          @getphonenumber="getPhoneNumber"
        >
          <!-- <text class="iconfont hy-icon-wechat"></text> -->
          手机号快捷登录
        </u-button>
        <navigator
          open-type="navigateBack"
          hover-class="navigator-hover"
          style="text-align: center; color: #999"
        >
          取消
        </navigator>
        <!-- #endif -->
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { Md5 } from 'ts-md5'
import { useUserStore, useConfigStore } from '@/store'
import { baseApi, powerBankApi, userApi } from '@/api'
import logo from '@/static/ic_launcher.png'
import {
  isWeChat,
  getQueryVariable,
  generateId,
  isAlipayClient,
  generateAlipayAuthUrl
} from '@/utils/common'
import wxShare from '@/common/wechat-share'
// 密码显示控制
const showPassword = ref(false)
const userStore = useUserStore()
const configStore = useConfigStore()
const isWeChatOfficial = ref(true)
const zfbCode = ref()
const options = ref()
// #ifdef MP-WEIXIN
isWeChatOfficial.value = false
// #endif
const form = reactive({
  username: '',
  code: '',
  type: 10
})
const codeText = ref('')
const uCode = ref()
// 手机号验证
const telReg = /^1[3456789]\d{9}$/
function togglePassword() {
  showPassword.value = !showPassword.value
}
function mobileBlurFn() {
  if (form.username !== '') {
    if (!telReg.test(form.username)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
    }
  } else {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
  }
}
function clearFn() {
  form.username = ''
}

function switchLoginType(type: keyof typeof userApi.LOGIN_TYPE_ENUM) {
  form.type = userApi.LOGIN_TYPE_ENUM[type]
  form.code = ''
}
async function submit() {
  console.log('进入登录')

  if (form.username !== '') {
    if (!telReg.test(form.username)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
  } else {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  if (!form.code) {
    uni.showToast({
      title:
        form.type === userApi.LOGIN_TYPE_ENUM.PWD
          ? '请输入密码'
          : '请输入验证码',
      icon: 'none'
    })
    return
  }
  try {
    const { data } = await userApi.login({
      type: form.type,
      username: form.username,
      code:
        form.type === userApi.LOGIN_TYPE_ENUM.PWD
          ? Md5.hashStr(form.code)
          : form.code
    })

    userStore.syncSetToken(data.accessToken)
    await getUserInfo()
    console.log('支付宝中的openid', options.value, data.accessToken)
    if (options.value.groupCode) {
      uni.reLaunch({
        url: `/packageD/pages/chatGroup/c_qrJoinChatGroup?groupCode${options.value.groupCode}&gid=${options.value.gid}&cid=${options.value.cid}`
      })
    } else {
      uni.reLaunch({
        url: '/pages/launch/index?from=login'
      })
    }
    // if(userStore.hasLogin){
    //   console.log('支付宝中的openid5555', );

    // }

    if (!isWeChatOfficial.value) return
    if (!uni.getStorageSync('openid')) {
      await userStore.wxAuth()
      uni.setStorageSync('onlyGetOpenid', 'yes')
    }
  } catch {}
}
async function getUserInfo() {
  const { data } = await userApi.userInfo()
  userStore.syncSetUserInfo(data)
}
function getUserProfileFn() {
  uni.getUserProfile({
    desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    lang: 'zh_CN',
    success: (res) => {
      console.log(res)
    }
  })
}
async function getPhoneNumber(res: { detail: { code: any } }) {
  try {
    const { data } = await userApi.wxUserPhoneNumber({
      accessToken: userStore.wxAccessToken,
      code: res.detail.code
    })
    uni.redirectTo({
      url: `/pages/register/bindPhone?phone=${data.phoneNumber}`
    })
  } catch (err) {
    console.log('getNumber', err)
  }
}
async function handleWxWebLogin() {
  console.log('微信登录')
  await userStore.wxAuth()
  console.log('登录页面的code')
  const codeAuth = getQueryVariable('code')
  if (!codeAuth) {
    throw new Error('获取微信授权码失败')
  }
  await userStore.wxWebLogin(codeAuth) //获取openid
  const login_success: any = await userStore.hlhyLoginByOpenId()
  if (login_success.status) {
    uni.redirectTo({
      url: '/pages/launch/index?from=login'
    })
  }
}

function toRegister() {
  uni.navigateTo({
    url: '/pages/register/register-app'
  })
}
async function sendSmsCode() {
  if (form.username !== '') {
    if (!telReg.test(form.username)) {
      uni.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
  } else {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  if (uCode.value.canGetCode) {
    try {
      const { data } = await baseApi.smsSend({
        type: 2,
        phone: form.username
      })
      uCode.value.start()
    } catch {}
  }
}
function codeChange(text: string) {
  codeText.value = text
}

// h5端 阿里云一键登录
function isWifi() {
  let isWifi = false
  uni.getNetworkType({
    success: (res) => {
      isWifi = res.networkType === 'wifi'
    }
  })
  return isWifi
}
// const phoneNumberServer = new PhoneNumberServer()
const getAuthToken = async () => {
  const { data, code } = await userApi.getAuthToken({
    origin: window.location.origin,
    url: 'https://wap.blacksilverscore.com/#/pages/register/bindPhone'
  })
  if (code === 200) {
    return data
  }
  throw new Error('获取accessToken或jwtToken失败')
}
const checkLogin = async (accessToken: any, jwtToken: any) => {
  return new Promise((resolve, reject) => {
    phoneNumberServer.checkLoginAvailable({
      accessToken,
      jwtToken,
      success(res: any) {
        console.log('身份鉴权成功, 可唤起登录界面', res)
        resolve(res)
      },
      error(res: any) {
        console.log('身份鉴权失败', res)
        if (res.msg) {
          uni.showToast({
            icon: 'none',
            title: res.msg
          })
        }
        reject(res)
      }
    })
  })
}
function getSpToken() {
  phoneNumberServer.getLoginToken({
    // 成功回调
    async success(res: any) {
      const { spToken } = res
      const { data } = await userApi.getPhoneWithToken({ spToken })
      const { mobile } = data
      form.username = mobile
      phoneNumberServer.closeLoginPage()
      await doRegister()
    },
    // 失败回调
    error(res: any) {
      uni.hideLoading()
      if (isWifi()) {
        uni.showModal({
          title: '提示',
          content: '请关闭wifi后重试',
          showCancel: false,
          success: ({ confirm }) => {
            if (confirm) {
              uni.showLoading()
              setTimeout(() => {
                window.location.reload()
              }, 2000)
            }
          }
        })
      }
      console.log('error===>', res)
    },
    // 授权页状态监听函数
    watch(status: any, data: any) {
      console.log(status, data)
    },
    // 配置选项
    authPageOption: {
      navText: '一键登录',
      subtitle: '', // 副标题
      btnText: '立即登录',
      agreeSymbol: '、',
      showCustomView: false,
      customView: {
        element:
          '<div class="btn_box other" onclick="clickEvent()">切换其他登录方式</div>',
        style:
          '.btn_box.other{background: #fff; color: #f00;text-align: center}',
        js: 'function clickEvent(){alert(666666)}'
      },
      privacyBefore: '我已阅读并同意',
      isDialog: true, // 是否是弹窗样式
      manualClose: true // 是否手动关闭弹窗/授权页
    }
  })
}
async function getPhoneByAliSdk() {
  uni.showLoading()
  const { jwtToken, accessToken } = await getAuthToken()
  if (
    await checkLogin(accessToken, jwtToken).finally(() => {
      uni.hideLoading()
    })
  ) {
    await getSpToken()
  }
  uni.hideLoading()
}

async function doRegister() {
  try {
    uni.showLoading({
      title: '登录中',
      mask: true
    })
    const params = {
      loginType: userApi.LOGIN_TYPE_ENUM.WECHATPUBLIC,
      phone: form.username,
      code: '123456', // 走一键登录不校验验证码了
      password: Md5.hashStr(generateId()),
      openId: userStore.openid,
      unionId: userStore.unionid,
      nickname: userStore.wxUserInfo.nickname || '',
      avatar: userStore.wxUserInfo.headimgurl || ''
    }
    const shopCode = uni.getStorageSync('shopCode')
    const shareCode = uni.getStorageSync('shareCode')
    if (shareCode) {
      params.inviteCode = shareCode
    } else if (shopCode) {
      params.shopCode = shopCode
    }
    const { data } = await userApi.register(params)
    userStore.syncSetToken(data.accessToken)
    await userStore.getUserInfo()
    // #ifdef H5
    uni.redirectTo({
      url: '/pages/launch/index?from=login'
    })
    // #endif
    uni.hideLoading()
  } catch {}
}
// =======END

onLoad(async (option) => {
  options.value = option
  // #ifdef H5
  isWeChatOfficial.value = isWeChat()
  if (isWeChatOfficial.value) {
    const code = getQueryVariable('code')
    if (code) {
      console.log('重定向的login', code)
      await userStore.wxWebLogin(code)
      const login_success = await userStore.loginByOpenId()
      if (login_success) {
        uni.redirectTo({
          url: '/pages/launch/index?from=login'
        })
      } else {
        uni.redirectTo({
          url: '/pages/register/register-app'
        })
      }
    } else {
      // console.log('首次进入login', option)
      // options.value = option
    }
  }
  // #endif
})
</script>

<style lang="scss" scoped>
.container {
  background: #fff;
  overflow: hidden;
  min-height: 100vh;
}

.placeholderStyle {
  color: #d3dbe0;
  font-size: 34rpx;
  font-weight: normal;
}

.logo {
  display: block;
  width: 200rpx;
  height: 200rpx;
  margin: 0 auto;
  margin-top: 100rpx;
  border-radius: 10rpx;
}

.form {
  padding: 150rpx 75rpx;
}

.loginType {
  color: #a1a1a1;
}

.inputBox {
  position: relative;
  border-bottom: 2rpx solid #e6ecf0;
  margin-bottom: 20rpx;

  &.flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .label {
    font-size: 36rpx;
    color: #333;
    font-weight: bold;
  }

  .inpt {
    display: block;
    width: 500rpx;
    padding: 30rpx 0;
    color: #242426;
    font-weight: bold;
    font-size: 34rpx;
  }

  .close {
    width: 28rpx;
    height: 28rpx;
    position: absolute;
    bottom: 0;
    right: 0;
    top: 0;
    margin: auto;
    z-index: 2;
  }
  // 新增密码眼睛图标样式
  .eye-icon {
    position: absolute;
    bottom: 0;
    right: 0;
    top: 0;
    margin: auto;
    z-index: 2;
    color: #999;
  }

  // 密码框样式特殊处理
  &.pwd-box {
    .inpt.code {
      width: 450rpx; // 留出眼睛图标的空间
    }
  }
}

.hy-btn {
  margin: 70rpx 0 30rpx 0;

  &.wx {
    margin-top: 40rpx;
    background: transparent;
    color: #ff6c18;
  }

  .hy-icon-wechat {
    color: #ff6c18;
    margin-right: 15rpx;
    font-size: 40rpx;
  }
}

.signuptips {
  font-size: 24rpx;
  margin-top: 50rpx;
  color: #a1a1a1;
  text-align: center;
  position: absolute;
  bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  width: 100%;
  left: 0;

  text {
    color: #ff6c18;
  }
}
</style>
